import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';
import {ConfigService} from "../config.service";
import { AuthService } from '../auth.service';

@Injectable({
  providedIn: 'root'
})
export class Customer2Service {

    private baseUrl = this.configService.api.url + '/customers';  // URL to web API
    private subject: any = {
        create: new Subject<any>(),
        delete: new Subject<any>(),
        update: new Subject<any>(),
        refresh: new Subject<any>()
    };

    constructor(private http: HttpClient, private authService: AuthService, private configService: ConfigService) {
    }

    on(event, callback) {
        return this.subject[event].subscribe(value => callback(value));
    }

    emit(event, value: any) {
        return this.subject[event].next(value);
    }

    create(customer): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        customer._id = this.configService.guid();
        return this.http.post(this.baseUrl + '/create', {customer: customer}, options);
    }

    delete(id: string): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        return this.http.post(this.baseUrl + '/' + id + '/remove', options);
    }

    update(customer): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        return this.http.post(this.baseUrl + '/' + customer._id + '/update', {customer: customer}, options);
    }

    getAll(): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        return this.http.get(this.baseUrl + '/', options);
    }

    getOne(id: string): Observable<any> {
        let headers = this.authService.getHeader();
        let options = {headers: headers};
        return this.http.get(this.baseUrl + '/detail/' + id, options);
    }

}
